package com.controller;

import com.dao.IMessageDAO;
import com.dao.IRevertDAO;
import com.vo.Message;
import com.vo.Revert;
import com.vo.Students;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/messages")
public class MessageController {
    @Autowired
    private IMessageDAO messageDAO;

    @Autowired
    private IRevertDAO revertDAO;

    @GetMapping
    public String getAllMessages(Model model) {
        List<Message> messages = messageDAO.getAllMessages();
        model.addAttribute("messages", messages);
        return "messages/list";
    }

    @GetMapping("/{id}")
    public String getMessage(@PathVariable int id, Model model) {
        // 获取留言
        Message message = messageDAO.getMessageById(id);
        if (message == null) {
            return "redirect:/messages";
        }

        // 获取回复列表（添加调试日志）
        List<Revert> reverts = revertDAO.getRevertsByMessage(id);
        System.out.println("加载留言ID=" + id + "的回复，数量：" + reverts.size());

        // 准备表单对象
        Revert newRevert = new Revert();
        newRevert.setMessageID(id); // 关键：预设messageID

        model.addAttribute("message", message);
        model.addAttribute("reverts", reverts);
        model.addAttribute("newRevert", newRevert);

        return "messages/detail";
    }

    @GetMapping("/add")
    public String addMessagePage(Model model) {
        model.addAttribute("message", new Message());
        return "messages/add";
    }

    @PostMapping
    public String addMessage(Message message, HttpSession session) {
        Students user = (Students) session.getAttribute("currentUser");
        message.setWriter(user.getStudentName());
        message.setWriteDate(new Date());
        messageDAO.addMessage(message);
        return "redirect:/messages";
    }

    @PostMapping("/{id}/delete")
    public String deleteMessage(@PathVariable int id, HttpSession session) {
        Students user = (Students) session.getAttribute("currentUser");
        Message message = messageDAO.getMessageById(id);

        if (message != null && message.getWriter().equals(user.getStudentName())) {
            // 先删除相关回复
            revertDAO.deleteRevertsByMessage(id);
            // 再删除留言
            messageDAO.deleteMessage(id);
        }
        return "redirect:/messages";
    }
}